package com.gh.mp.eduservice.controller;

import com.aliyun.oss.OSSClient;
import com.gh.mp.edu.common.R;
import com.gh.mp.eduservice.handler.ConstantPropertiesUtil;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @Author Eric
 * @Date 2021/4/17 20:55
 * @Version 1.0
 **/
@RestController
@RequestMapping("/eduservice/oss")
@CrossOrigin
public class FileUploadController {


    @PostMapping("uploadFile")
    public R uploadTeacherImg(@RequestParam("file") MultipartFile file,
                              @RequestParam(value = "host", required = false) String host) {
        try {
            String filename = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString();
            filename = uuid + filename;
            //获取当前时间
            String filepath = new DateTime().toString("yyyy/MM/dd");
            //拼接文件完整名称
            String hostName = ConstantPropertiesUtil.HOST;
            if (StringUtils.isEmpty(host)) {
                filename = filepath + "/"+ hostName + "/" + filename  ;
            } else {
                filename = filepath + "/" + host + "/" + filename;
            }
            InputStream in = file.getInputStream();

            // 创建OSSClient实例。
            OSSClient ossClient = new OSSClient(ConstantPropertiesUtil.ENDPOINT, ConstantPropertiesUtil.KEYID, ConstantPropertiesUtil.KEYSECRET);
            // 填写本地文件的完整路径。如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件流。
            //  InputStream inputStream = new FileInputStream("D:\\localpath\\examplefile.txt");
            // 填写Bucket名称和Object完整路径。Object完整路径中不能包含Bucket名称。
            ossClient.putObject(ConstantPropertiesUtil.BUCKEYNAME, filename, in);
            // 关闭OSSClient。
            ossClient.shutdown();
            //https://eric123.oss-cn-shanghai.aliyuncs.com/0406_1.jpg
            String path = "http://" + ConstantPropertiesUtil.BUCKEYNAME + "." + ConstantPropertiesUtil.ENDPOINT + "/" + filename;
            return R.ok().data("imageUrl", path);
        } catch (Exception e) {
            return R.error();
        }
    }
}
